﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraCharts;
using DevExpress.Utils;
using TierService;
using OrderMgr.SysSetting;
using System.Data.SqlClient;
using TierApplication;


namespace OrderMgr.OrderInfo
{
    public partial class frmBuyPayAppDetail : TierService.frmTemplate
    {
        #region "Member Variables"
        public string sFuncID;
        public TierService.Utility.OperateMode OpMode;
        public string sUserID;
        public string _OrderID = "";
        public Utility.OrderType _OrderType;
        public Utility.OrderStatus _AuditStatus;

        T_Order mOrder = new T_Order();
        SqlDataAdapter sdaOrderDetail = new SqlDataAdapter();
        DataSet dsOrderDetail = new DataSet();

        #endregion

        public frmBuyPayAppDetail()
        {
            InitializeComponent();
        }

        private void frmBuyAuditDetail_Load(object sender, EventArgs e)
        {
            initForm();

            switch (OpMode)
            {
                case Utility.OperateMode.Query:
                    btnSave.Visible = false;
                    btnProductAdd.Visible = false;
                    btnProductDelete.Visible = false;
                    btnAudit.Visible = false;
                    btnDeAudit.Visible = false;
                    showInfo(_OrderID);
                    break;
                case Utility.OperateMode.Insert:
                    txtOrderDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    txtOrderUserID.EditValue = TierService.Utility.gUserID;
                    txtOrderType.EditValue = ((int)_OrderType).ToString();
                    txtDepotID.EditValue = ((int)Utility.DepotType.Material).ToString();
                    txtRemark.Size = new Size(742, 83);
                    txtRemark.Location = new Point(82, 81);
                    BindOrderDetailLocal();
                    break;
                case Utility.OperateMode.Update:
                    btnSave.Enabled = true;
                    showInfo(_OrderID);
                    break;
                case Utility.OperateMode.Delete:
                    break;
                default:
                    break;
            }

        }

        private void initForm()
        {
            Utility.DataToLookupComboxEx(txtOrderType, C_DMB.GetListByType(C_DMB.DType.OrderType.ToString()), "CodeID", "CodeName");
            Utility.DataToLookupComboxEx(txtDepotID, C_DMB.GetListByType(C_DMB.DType.DepotType.ToString()), "CodeID", "CodeName");
            Utility.DataToLookupComboxEx(txtOrderUserID, (new P_User()).GetList(""), "UserID", "UserName");
            Utility.DataToLookupComboxEx(txtAuditUserID, (new P_User()).GetList(""), "UserID", "UserName");
            Utility.DataToLookupComboxEx(txtPayUserID, (new P_User()).GetList(""), "UserID", "UserName");
            Utility.DataToLookupComboxEx(txtSupplierID, (new T_Supplier()).GetList(""), "SupplierID", "SupplierName");
            Utility.DataToLookupComboxEx(txtPayType, C_DMB.GetListByType(C_DMB.DType.PayType.ToString()), "CodeID", "CodeName");

            txtOrderUserID.Enabled = false;
            txtOrderType.Enabled = false;

        }


        private void showInfo(string sID)
        {
            mOrder.GetModel(sID);
            this.txtOrderID.Text = mOrder.OrderID;
            if (mOrder.OrderDate != null)
                this.txtOrderDate.DateTime = mOrder.OrderDate.Value;
            this.txtOrderUserID.EditValue = mOrder.OrderUserID;
            this.txtOrderType.EditValue = mOrder.OrderType;
            this.txtDepotID.EditValue = mOrder.DepotID;
            this.txtAuditUserID.EditValue = mOrder.AuditUserID;
            if (mOrder.AuditDate != null)
                this.txtAuditDate.DateTime = mOrder.AuditDate.Value;
            this.txtRemark.Text = mOrder.Remark;
            this.txtSupplierID.EditValue = mOrder.SupplierID;

            this.txtContractNo.Text = mOrder.ContractNo;
            this.txtPayType.EditValue = mOrder.PayType.ToString();
            if (mOrder.PayRstDate != null)
                this.txtPayRstDate.DateTime = mOrder.PayRstDate.Value;
            this.txtPayerFullName.Text = mOrder.PayerFullName;
            this.txtPayerBank.Text = mOrder.PayerBank;
            this.txtPayeBankAccount.Text = mOrder.PayeBankAccount;
            this.txtPayFee.Text = mOrder.PayFee.ToString();
            this.txtPayReason.Text = mOrder.PayReason;
            this.txtPayUserID.EditValue = mOrder.PayUserID;

            if (txtPayerFullName.Text == "")
            {
                T_Supplier mSupplier = new T_Supplier();
                mSupplier.GetModel(mOrder.SupplierID);
                this.txtPayerFullName.Text = mSupplier.PayerFullName;
                this.txtPayerBank.Text = mSupplier.PayerBank;
                this.txtPayeBankAccount.Text = mSupplier.PayeBankAccount;
            }

            if (mOrder.PayAuditOpinion != "")
            {
                txtDeAuditReson.Visible = true;
                txtDeAuditReson.Text = "审核退回原因："+ mOrder.PayAuditOpinion;
            }

            //*****************Order Detail*****************//
            BindOrderDetail();

            switch (_AuditStatus)
            {
                case Utility.OrderStatus.S0Input:
                    lblAuditDate.Visible = false;
                    lblAuditUserID.Visible = false;
                    txtAuditDate.Visible = false;
                    txtAuditUserID.Visible = false;
                    break;
                case Utility.OrderStatus.S1Auditing:
                    txtAuditDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    txtAuditUserID.EditValue = TierService.Utility.gUserID;
                    break;
                case Utility.OrderStatus.S2Audited:
                    txtPayRstDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    txtPayUserID.EditValue = TierService.Utility.gUserID;
                    break;
                case Utility.OrderStatus.All:
                    break;
                default:
                    break;
            }

        }
        private void GetFormReturValue(string str)
        {
            string sID = str;
            if (sID != "")
            {
                showInfo(sID);
            }
        }


        private void btnClose_Click(object sender, EventArgs e)
        {
            //Close();
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            mOrder.OrderID = this.txtOrderID.Text;
            mOrder.OrderDate = DateTime.Parse(this.txtOrderDate.Text);
            mOrder.OrderUserID = (string)this.txtOrderUserID.EditValue;
            mOrder.OrderType = (string)this.txtOrderType.EditValue;
            mOrder.DepotID = (string)this.txtDepotID.EditValue;
            mOrder.Remark = this.txtRemark.Text;
            mOrder.Sign = 0;
            mOrder.Transfer = "0";

            if (_AuditStatus == Utility.OrderStatus.S2Audited)
            {
                mOrder.PayUserID = (string)this.txtPayUserID.EditValue;
                mOrder.PayRstDate = DateTime.Parse(this.txtPayRstDate.Text);
            }
            mOrder.ContractNo = this.txtContractNo.Text;
            mOrder.PayType = (string)this.txtPayType.EditValue;
            mOrder.PayerFullName = this.txtPayerFullName.Text;
            mOrder.PayerBank = this.txtPayerBank.Text;
            mOrder.PayeBankAccount = this.txtPayeBankAccount.Text;
            mOrder.PayFee = this.txtPayFee.Value;
            mOrder.PayReason = this.txtPayReason.Text;

            //if ((mOrder.CustTypeID == "") || (mOrder.CustTypeID == null))
            //{
            //    XtraMessageBox.Show("请选择订单类别");
            //    return;
            //}
            //if ((mOrder.CustName == ""))
            //{
            //    XtraMessageBox.Show("请输入订单名称");
            //    txtCustName.Focus();
            //    return;
            //}

            switch (OpMode)
            {
                case TierService.Utility.OperateMode.Insert:
                    try
                    {
                        _OrderID = AddOrderDetail();
                        if (_OrderID == "")
                        {
                            break;
                        }
                        txtOrderID.Text = _OrderID;
                        BindOrderDetail();
                        OpMode = Utility.OperateMode.Update;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("新增出错,错误原因为:" + ex.Message);
                        break;
                    }
                    MessageBox.Show("订单信息新增成功!");
                    //DialogResult = DialogResult.OK;
                    break;
                case TierService.Utility.OperateMode.Update:
                    try
                    {
                        // mCustomer.CustID = txtCustID.Text;
                        mOrder.Update();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("订单信息修改出错,错误原因为:" + ex.Message);
                        break;
                    }

                    MessageBox.Show("订单信息修改成功!");
                    //DialogResult = DialogResult.OK;
                    break;
                default:
                    break;
            }
            btnSubmitAudit.Visible = true;
        }

        private string AddOrderDetail()
        {
            using (SqlConnection conn = new SqlConnection(DBUtility.PubConstant.ConnectionString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    //保存客户信息
                    //SaveCustomerInfo(txtCustomerID.Text);
                    mOrder.OrderID = Utility.GetSeqval(Utility.SeqName.OrderID.ToString());
                    //mOrder.Add();
                    string sSql = mOrder.GetAddSql();
                    try
                    {
                        cmd.CommandText = sSql;
                        int rows = cmd.ExecuteNonQuery();
                        if (rows < 1)
                        {
                            return "";
                        }
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        _OrderID = "";
                        FileLog.WriteTextToFile("错误SQL语句为:" + sSql + " " + e.Message);
                        throw new Exception("错误SQL语句为:" + sSql + " " + e.Message);
                    }
                    _OrderID = mOrder.OrderID;

                    //增加明细信息
                    for (int i = 0; i < gvOrderDetail.RowCount; i++)
                    {
                        T_OrderDetail mOrderDetail = new T_OrderDetail();
                        mOrderDetail.OrderID = mOrder.OrderID;
                        mOrderDetail.OrderDetailID = gvOrderDetail.GetRowCellValue(i, clOrderDetailID).ToString();
                        mOrderDetail.ProductID = gvOrderDetail.GetRowCellValue(i, clProductID).ToString();
                        try
                        {
                            mOrderDetail.UnitPrice = decimal.Parse(gvOrderDetail.GetRowCellValue(i, clUnitPrice).ToString());
                        }
                        catch (Exception)
                        {
                            mOrderDetail.UnitPrice = 0;
                        }
                        try
                        {
                            mOrderDetail.PlnQuantity = int.Parse(gvOrderDetail.GetRowCellValue(i, clPlnQuantity).ToString());
                        }
                        catch (Exception)
                        {
                            mOrderDetail.PlnQuantity = 0;
                        }
                        try
                        {
                            mOrderDetail.ShpQuantity = int.Parse(gvOrderDetail.GetRowCellValue(i, clShpQuantity).ToString());
                        }
                        catch (Exception)
                        {
                            mOrderDetail.ShpQuantity = 0;
                        }

                        mOrderDetail.ActQuantity = int.Parse(gvOrderDetail.GetRowCellValue(i, clActQuantity).ToString());
                        try
                        {
                            mOrderDetail.BckQuantity = int.Parse(gvOrderDetail.GetRowCellValue(i, clBckQuantity).ToString());
                        }
                        catch (Exception)
                        {
                            mOrderDetail.BckQuantity = 0;
                        }
                        //mOrderDetail.Discount = int.Parse(gvOrderDetail.GetRowCellValue(i, clDiscount).ToString());
                        //mOrderDetail.SumPrice = decimal.Parse(gvOrderDetail.GetRowCellValue(i, clSumPrice).ToString());
                        //mOrderDetail.Add();
                        string sDetailSql = mOrderDetail.GetAddSql();
                        try
                        {
                            cmd.CommandText = sDetailSql;
                            int rows = cmd.ExecuteNonQuery();
                            if (rows < 1)
                            {
                                return "";
                            }
                        }
                        catch (System.Data.SqlClient.SqlException e)
                        {
                            _OrderID = "";
                            FileLog.WriteTextToFile("错误SQL语句为:" + sSql + " " + e.Message);
                            throw new Exception("错误SQL语句为:" + sSql + " " + e.Message);
                        }
                    }

                    tx.Commit();
                    return _OrderID;
                }
                catch (Exception ex)
                {
                    tx.Rollback();
                    MessageBox.Show("新增出错,错误原因为:" + ex.Message);
                    return "";
                }
            }
        }

        private void btnProductAdd_Click(object sender, EventArgs e)
        {
            int currentRow;
            currentRow = gvOrderDetail.FocusedRowHandle;
            if (currentRow < 0)
                currentRow = gvOrderDetail.GetDataRowHandleByGroupRowHandle(currentRow);
            gvOrderDetail.AddNewRow();
            if (gvOrderDetail.RowCount < 1) return;
            DataRow dr = gvOrderDetail.GetDataRow(gvOrderDetail.FocusedRowHandle);

            dr["OrderDetailID"] = Utility.GetSeqNextval(Utility.SeqName.OrderDetailID.ToString()).ToString();
            if (gvOrderDetail.SortInfo.GroupCount == 0) return;

            //Initialize group values
            foreach (DevExpress.XtraGrid.Columns.GridColumn groupColumn in gvOrderDetail.GroupedColumns)
            {
                object val = gvOrderDetail.GetRowCellValue(currentRow, groupColumn);
                gvOrderDetail.SetRowCellValue(gvOrderDetail.FocusedRowHandle, groupColumn, val);
            }

            gvOrderDetail.UpdateCurrentRow();
            gvOrderDetail.ShowEditor();
        }

        private void btnProductDelete_Click(object sender, EventArgs e)
        {
            if (gvOrderDetail.RowCount < 1) return;

            if (MessageBox.Show("是否要删除此记录", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                return;


            gvOrderDetail.DeleteRow(gvOrderDetail.FocusedRowHandle);
        }

        private void btnProductQuery_Click(object sender, EventArgs e)
        {
            if (gvOrderDetail.RowCount < 1) return;
            DataRow dr = gvOrderDetail.GetDataRow(gvOrderDetail.FocusedRowHandle);
            string sID = dr["ProductID"].ToString();

            T_Product mProduct = new T_Product();
            mProduct.GetModel(sID);
            string sProductType = mProduct.ProductProp;

            frmProductDetail fDetail = new frmProductDetail();
            fDetail.OpMode = TierService.Utility.OperateMode.Query;
            if (sProductType == "1")
                fDetail.gProductType = Utility.ProductType.MProduct;
            else
                fDetail.gProductType = Utility.ProductType.Product;

            fDetail._ProductID = sID;
            fDetail.ShowDialog();
        }

        private void rsbtnProductID_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmProductList fDetail = new frmProductList();
            fDetail._OrderType = _OrderType;
            if (fDetail.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                int currentRow;
                currentRow = gvOrderDetail.FocusedRowHandle;
                //if (currentRow < 0)
                //    currentRow = gvOrderDetail.GetDataRowHandleByGroupRowHandle(currentRow);
                //gvOrderDetail.AddNewRow();
                //if (gvOrderDetail.RowCount < 1) return;
                //DataRow dr = gvOrderDetail.GetDataRow(gvOrderDetail.FocusedRowHandle);

                //dr["ProductID"] = fDetail._ProductID;

                gvOrderDetail.SetFocusedValue(fDetail._ProductID);

            }
        }

        private void BindOrderDetailLocal()
        {
            DataTable dtOrderDetail = new TdsOrder.TOrderDetailDataTable();
            gcOrderDetail.DataSource = dtOrderDetail;
        }

        private void BindOrderDetail()
        {

            if (_OrderID == "") return;

            SqlConnection conn = new SqlConnection(DBUtility.DbHelperSQL.connectionString);

            SqlCommand cmd;
            SqlParameter pram;
            StringBuilder strSql = new StringBuilder();

            string sSql = "";
            sSql = "Select a.OrderDetailID,a.OrderID,a.ProductID,Floor(a.PlnQuantity) PlnQuantity,Floor(a.ShpQuantity) ShpQuantity,Floor(a.ActQuantity) ActQuantity,Floor(a.BckQuantity) BckQuantity,a.UnitPrice,(a.ActQuantity*a.UnitPrice) SumPrice, a.ProductNo,";
            sSql = sSql + " b.UnitName,b.SupplierName,b.Spec1,b.ProductName";
            sSql = sSql + " from T_OrderDetail a,S_Product b where a.ProductID=b.ProductID and a.OrderID='" + _OrderID + "'";
            cmd = new SqlCommand(sSql, conn);
            sdaOrderDetail.SelectCommand = cmd;

            strSql.Append("insert into T_OrderDetail(");
            strSql.Append("OrderDetailID,OrderID,ProductID,PlnQuantity,ShpQuantity,ActQuantity,BckQuantity,UnitPrice)");
            strSql.Append(" values (");
            strSql.Append("@OrderDetailID,@OrderID,@ProductID,@PlnQuantity,@ShpQuantity,@ActQuantity,@BckQuantity,@UnitPrice)");
            cmd = new SqlCommand(strSql.ToString(), conn);
            pram = new SqlParameter("@OrderID", SqlDbType.VarChar, 20);
            pram.Value = _OrderID;
            cmd.Parameters.Add(pram);
            cmd.Parameters.Add("@OrderDetailID", SqlDbType.VarChar, 10, "OrderDetailID");
            cmd.Parameters.Add("@ProductID", SqlDbType.VarChar, 10, "ProductID");
            cmd.Parameters.Add("@PlnQuantity", SqlDbType.Int, 4, "PlnQuantity");
            cmd.Parameters.Add("@ShpQuantity", SqlDbType.Int, 4, "ShpQuantity");
            cmd.Parameters.Add("@ActQuantity", SqlDbType.Int, 4, "ActQuantity");
            cmd.Parameters.Add("@BckQuantity", SqlDbType.Int, 4, "BckQuantity");
            cmd.Parameters.Add("@UnitPrice", SqlDbType.Decimal, 9, "UnitPrice");
            sdaOrderDetail.InsertCommand = cmd;

            strSql.Remove(0, strSql.Length);
            strSql.Append("update T_OrderDetail set ");
            //strSql.Append("ProductID=@ProductID,");
            strSql.Append("ProductID=@ProductID,");
            strSql.Append("PlnQuantity=@PlnQuantity,");
            strSql.Append("ShpQuantity=@ShpQuantity,");
            strSql.Append("ActQuantity=@ActQuantity,");
            strSql.Append("BckQuantity=@BckQuantity,");
            strSql.Append("UnitPrice=@UnitPrice");
            strSql.Append(" where OrderDetailID=@OrderDetailID ");
            cmd = new SqlCommand(strSql.ToString(), conn);
            cmd.Parameters.Add("@OrderDetailID", SqlDbType.VarChar, 10, "OrderDetailID");
            cmd.Parameters.Add("@ProductID", SqlDbType.VarChar, 10, "ProductID");
            cmd.Parameters.Add("@PlnQuantity", SqlDbType.Int, 4, "PlnQuantity");
            cmd.Parameters.Add("@ShpQuantity", SqlDbType.Int, 4, "ShpQuantity");
            cmd.Parameters.Add("@ActQuantity", SqlDbType.Int, 4, "ActQuantity");
            cmd.Parameters.Add("@BckQuantity", SqlDbType.Int, 4, "BckQuantity");
            cmd.Parameters.Add("@UnitPrice", SqlDbType.Decimal, 9, "UnitPrice");
            sdaOrderDetail.UpdateCommand = cmd;

            cmd = new SqlCommand("delete T_OrderDetail where OrderDetailID=@OrderDetailID", conn);
            cmd.Parameters.Add("@OrderDetailID", SqlDbType.VarChar, 10, "OrderDetailID");
            sdaOrderDetail.DeleteCommand = cmd;


            dsOrderDetail.Clear();

            sdaOrderDetail.Fill(dsOrderDetail);
            gcOrderDetail.DataSource = dsOrderDetail.Tables[0];
            //gvOrdersDetail.BestFitColumns();
        }

        private void gvOrderDetail_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            DataRow dr = gvOrderDetail.GetDataRow(e.RowHandle);
            double UnitPrice, Quantity, Discount, SumPrice;

            try
            {
                UnitPrice = double.Parse(dr["UnitPrice"].ToString());
            }
            catch (Exception)
            {
                UnitPrice = 0;
            }

            try
            {
                Quantity = int.Parse(dr["ActQuantity"].ToString());
            }
            catch (Exception)
            {
                Quantity = 0;
            }

            SumPrice = UnitPrice * Quantity;
            //SumPrice = SumPrice - SumPrice * (100 - Discount) / 100;

            if (e.Column != clSumPrice)
            {
                dr["SumPrice"] = SumPrice.ToString("00000000000.00");
            }


            if (e.Column == clProductID)
            {
                string sProductID = dr["ProductID"].ToString();
                T_Product mProduct = new T_Product();
                mProduct.GetModel(sProductID);
                dr["ProductName"] = mProduct.ProductName;
                dr["PlnQuantity"] = 1;
                dr["ActQuantity"] = 1;
                dr["ShpQuantity"] = 1;
                dr["BckQuantity"] = 0;
                dr["SupplierName"] = mProduct.SupplierName;
                dr["UnitName"] = mProduct.UnitName;
                dr["UnitPrice"] = mProduct.UnitPrice;
                dr["SumPrice"] = mProduct.UnitPrice.ToString();
            }
        }

        private void btnAudit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否要审核此单据", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                return;
            string sOrderID = txtOrderID.Text;

            T_Order mOrder = new T_Order();
            mOrder.Audit(sOrderID, Utility.gUserID);
            MessageBox.Show("审核成功");
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void btnDeAudit_Click(object sender, EventArgs e)
        {
            if (txtPayReason.Text == "")
            {
                MessageBox.Show("请输入退回原因");
                txtPayReason.Focus();
                return;
            }

            if (MessageBox.Show("是否要退回此单据?", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                return;


            string sOrderID = txtOrderID.Text;

            T_Order mOrder = new T_Order();
            mOrder.DeAudit(sOrderID, Utility.gUserID, txtPayReason.Text);
            MessageBox.Show("审核退回成功");
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void btnSubmitAudit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否要将此单据提交审核吗？", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                return;
            string sOrderID = txtOrderID.Text;
            T_Order mOrder = new T_Order();
            mOrder.SubmitAudit(sOrderID,Utility.OrderStatus.S3PayApped);
            MessageBox.Show("单据提交审核成功");
            Close();
        }

    }
}